{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "1fe3b366",
   "metadata": {},
   "source": [
    "### 使用type()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d508135e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "int"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(123)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "7a2542f4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "str"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type('123')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "45217bed",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "NoneType"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abc2b9a4",
   "metadata": {},
   "source": [
    "如果一个变量指向函数或者类，也可以用type()判断："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e9a86f1a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "builtin_function_or_method"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(abs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8570811e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "__main__.Animal"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class Animal(object):\n",
    "    def run(self):\n",
    "        print('cool')\n",
    "a = Animal()\n",
    "type(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5abef69f",
   "metadata": {},
   "source": [
    "判断基本类型可以直接写int，str等，要判断一个对象是否是函数，可以使用types模块中定义的常量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "647f6825",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import types\n",
    "def fn():\n",
    "    pass\n",
    "type(fn) == types.FunctionType"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6594a165",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(abs) == types.BuiltinFunctionType"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "a518b61f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(lambda x: x) == types.LambdaType"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "5d423321",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(x for x in range(10)) == types.GeneratorType"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67c70887",
   "metadata": {},
   "source": [
    "### 使用isinstance()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e31e5970",
   "metadata": {},
   "source": [
    "isinstance()会更加方便，建议优先使用该方法。并且还可以判断一个变量是否是某些类型中的一种，比如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c8caf37d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isinstance([1,2,3], (list,tuple))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3cf25e67",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isinstance((1,2,3), (list, tuple))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed0ff4af",
   "metadata": {},
   "source": [
    "### 使用dir()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbc40129",
   "metadata": {},
   "source": [
    "如果获得一个对象的所有属性和方法，可以使用dir()函数，它返回一个包含字符串的list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e3693a97",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__add__',\n",
       " '__class__',\n",
       " '__contains__',\n",
       " '__delattr__',\n",
       " '__dir__',\n",
       " '__doc__',\n",
       " '__eq__',\n",
       " '__format__',\n",
       " '__ge__',\n",
       " '__getattribute__',\n",
       " '__getitem__',\n",
       " '__getnewargs__',\n",
       " '__gt__',\n",
       " '__hash__',\n",
       " '__init__',\n",
       " '__init_subclass__',\n",
       " '__iter__',\n",
       " '__le__',\n",
       " '__len__',\n",
       " '__lt__',\n",
       " '__mod__',\n",
       " '__mul__',\n",
       " '__ne__',\n",
       " '__new__',\n",
       " '__reduce__',\n",
       " '__reduce_ex__',\n",
       " '__repr__',\n",
       " '__rmod__',\n",
       " '__rmul__',\n",
       " '__setattr__',\n",
       " '__sizeof__',\n",
       " '__str__',\n",
       " '__subclasshook__',\n",
       " 'capitalize',\n",
       " 'casefold',\n",
       " 'center',\n",
       " 'count',\n",
       " 'encode',\n",
       " 'endswith',\n",
       " 'expandtabs',\n",
       " 'find',\n",
       " 'format',\n",
       " 'format_map',\n",
       " 'index',\n",
       " 'isalnum',\n",
       " 'isalpha',\n",
       " 'isascii',\n",
       " 'isdecimal',\n",
       " 'isdigit',\n",
       " 'isidentifier',\n",
       " 'islower',\n",
       " 'isnumeric',\n",
       " 'isprintable',\n",
       " 'isspace',\n",
       " 'istitle',\n",
       " 'isupper',\n",
       " 'join',\n",
       " 'ljust',\n",
       " 'lower',\n",
       " 'lstrip',\n",
       " 'maketrans',\n",
       " 'partition',\n",
       " 'removeprefix',\n",
       " 'removesuffix',\n",
       " 'replace',\n",
       " 'rfind',\n",
       " 'rindex',\n",
       " 'rjust',\n",
       " 'rpartition',\n",
       " 'rsplit',\n",
       " 'rstrip',\n",
       " 'split',\n",
       " 'splitlines',\n",
       " 'startswith',\n",
       " 'strip',\n",
       " 'swapcase',\n",
       " 'title',\n",
       " 'translate',\n",
       " 'upper',\n",
       " 'zfill']"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dir('ABC')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd6444ab",
   "metadata": {},
   "source": [
    "类似__xxx__的属性和方法在python中都有特殊用途，比如__len__方法返回长度。\n",
    "在Python中，如果你调用len(),实际上，len函数内部，它自动去调用该对象的__len__方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "4532f35e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len('ABC')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "57d915e3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'ABC'.__len__()"
   ]
  },
  {
   "cell_type": "raw",
   "id": "77b59d24",
   "metadata": {},
   "source": [
    "我们自己写的类，如果也想用len的话，就自己写一个__len__()方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "bb6f08e9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "100"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class MyDog(object):\n",
    "    def __len__(self):\n",
    "        return 100\n",
    "dog = MyDog()\n",
    "len(dog)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ef9bde3e",
   "metadata": {},
   "source": [
    "剩下的都是普通属性或者方法，比如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "75935574",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'abc'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'ABC'.lower()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e84f16b",
   "metadata": {},
   "source": [
    "仅仅把属性和方法列出来是不够的，配合getattr(),setattr(),hasattr()，我们可以直接操作一个对象的状态："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "51619122",
   "metadata": {},
   "outputs": [],
   "source": [
    "class Myobject(object):\n",
    "    def __init__(self):\n",
    "        self.x = 9\n",
    "    def power(self):\n",
    "        return self.x * self.x\n",
    "obj = Myobject()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "0076b546",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hasattr(obj, 'x')  #有属性'x'么"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "92b11980",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "obj.x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "11ff45a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hasattr(obj, 'y') #有属性'y'么"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "3f25fac5",
   "metadata": {},
   "outputs": [],
   "source": [
    "setattr(obj, 'y', 19) #设置一个属性y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "49ea53ab",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hasattr(obj, 'y')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "142d7c74",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "19"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "obj.y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "7086b980",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "getattr(obj, 'x')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5eb88f05",
   "metadata": {},
   "source": [
    "可以传入一个default参数，如果属性不存在，就返回默认值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "fdcbd727",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "303"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "getattr(obj, 'z', 303)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79d0fad9",
   "metadata": {},
   "source": [
    "也可以获得对象的方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "d4387b9c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hasattr(obj, 'power')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "46e30d73",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bound method Myobject.power of <__main__.Myobject object at 0x00000299FE917940>>"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "getattr(obj, 'power')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4282c758",
   "metadata": {},
   "source": [
    "### 小结"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "34f88eb8",
   "metadata": {},
   "source": [
    "通过内置的一系列函数，我们可以对任意一个Python对象进行剖析，拿到内部的数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6e977fa8",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
